package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Transactional
    @Override
    public void addCart(ShoppingCartDTO shoppingCartDTO) {
        // 判断购物车数据库中是否存在该用户相应的商品
        // 查看之前是否存在于数据库
        ShoppingCart cart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO, cart);
        Long userId = BaseContext.getCurrentId();
        cart.setUserId(userId);
        ShoppingCart shoppingCart = shoppingCartMapper.selectExist(cart);
        if(shoppingCart == null) {
            shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(cart, shoppingCart);
            // 第一次插入
            // 插入的是菜品还是套餐
            if (shoppingCartDTO.getDishId() != null) {
                // 插入的是菜品
                // 根据菜品id获取菜品对象
                Dish dish = dishMapper.selectById(shoppingCartDTO.getDishId());
                shoppingCart.setName(dish.getName());
                // 赋值1还是+1需要先判断购物车数据库中是否存在该用户相应的商品
                // 还是需要判断是否用户存在该商品
                shoppingCart.setAmount(dish.getPrice());
                shoppingCart.setImage(dish.getImage());
            } else if (shoppingCartDTO.getSetmealId() != null) {
                // 插入的是套餐
                // 根据套餐id获取套餐信息
                Setmeal setmeal = setmealMapper.getById(shoppingCart.getSetmealId());
                shoppingCart.setName(setmeal.getName());
                shoppingCart.setImage(setmeal.getImage());
                shoppingCart.setAmount(setmeal.getPrice());
            }
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        }else {
            // 之前就存在
            shoppingCart.setNumber(shoppingCart.getNumber() + 1);
            shoppingCartMapper.updateNumber(shoppingCart);
        }
        // 最终目的: 插入一个购物车数据
    }

    /**
     * 查看购物车
     * @return
     */
    @Override
    public List<ShoppingCart> list() {
        return shoppingCartMapper.list(BaseContext.getCurrentId());
    }

    /**
     * 清空购物车
     */
    @Override
    public void clean() {
        shoppingCartMapper.clean(BaseContext.getCurrentId());
    }
}
